using System;
using System.Configuration;
using Hermes.Framework.FileSystem;
using Hermes.Framework.FileSystem.Local;
using Hermes.Framework.FileSystem.Ftp;

namespace Hermes.Framework.Test
{
    public class SimpleFileSystemFactory : INonTransactableFileSystemFactory
    {
        protected string GetAccount(string host)
        {
            return "root";
        }

        protected string GetPassword(string host)
        {
            return "root";
        }

        protected static bool IsLocalFileSystem(string url)
        {
            return url.StartsWith("file://");
        }

        public INonTransactableFileSystem GetFileSystem(string from, string to)
        {
            INonTransactableFileSystem fileSystemFrom = GetFileSystem(from);
            INonTransactableFileSystem fileSystemTo = GetFileSystem(to);

            if (IsLocalFileSystem(from) && IsLocalFileSystem(to))
            {
                return GetFileSystem(from);
            }
            else if (IsLocalFileSystem(from) && !IsLocalFileSystem(to))
            {
                return GetFileSystem(to);
            }
            else if (IsLocalFileSystem(to) && !IsLocalFileSystem(from))
            {
                return GetFileSystem(from);
            }
            else
            {
                return GetFileSystem(from);
            }
        }

        public INonTransactableFileSystem GetFileSystem(string strUrl)
        {
            if (strUrl.StartsWith("file://"))
            {
                return new LocalFileSystem();
            }
            else if(strUrl.StartsWith("ftp://"))
            {
                FtpFileSystem ftpFileSystem = new FtpFileSystem();

                Url url = new Url(strUrl);
                string account = ConfigurationSettings.AppSettings[url.Host];
                if(account == null) {
                    throw new ConfigurationException(string.Format("Account for FTP {0} is not configured.", url.Host));
                }
                string[] match = account.Split(new char[] { '/' });

                ConnectionInfo ci = new ConnectionInfo(url.Host, url.Port, match[0], match[1]);

                ftpFileSystem.Connect(ci);

                return ftpFileSystem;
            }

            throw new NotSupportedException("No suitable file system." + strUrl);
        }
    }
}
